/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.domain.UserFamilyMembers;
import me.zhengjie.request.ATMRContext;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.repository.UserFamilyMembersRepository;
import me.zhengjie.modules.system.service.UserFamilyMembersService;
import me.zhengjie.modules.system.service.dto.UserFamilyMembersDto;
import me.zhengjie.modules.system.service.dto.UserFamilyMembersQueryCriteria;
import me.zhengjie.modules.system.service.mapstruct.UserFamilyMembersMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author zhaoxiancheng
* @date 2023-10-17
**/
@Service
@RequiredArgsConstructor
public class UserFamilyMembersServiceImpl implements UserFamilyMembersService {

    private final UserFamilyMembersRepository userFamilyMembersRepository;
    private final UserFamilyMembersMapper userFamilyMembersMapper;

    @Override
    public Map<String,Object> queryAll(UserFamilyMembersQueryCriteria criteria, Pageable pageable){
        Page<UserFamilyMembers> page = userFamilyMembersRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(userFamilyMembersMapper::toDto));
    }

    @Override
    public List<UserFamilyMembersDto> queryAll(UserFamilyMembersQueryCriteria criteria){
        return userFamilyMembersMapper.toDto(userFamilyMembersRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public UserFamilyMembersDto findById(Long memberId) {
        UserFamilyMembers userFamilyMembers = userFamilyMembersRepository.findById(memberId).orElseGet(UserFamilyMembers::new);
        ValidationUtil.isNull(userFamilyMembers.getMemberId(),"UserFamilyMembers","memberId",memberId);
        return userFamilyMembersMapper.toDto(userFamilyMembers);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserFamilyMembersDto create(UserFamilyMembers resources) {
        UserFamilyMembersQueryCriteria criteria = new UserFamilyMembersQueryCriteria();
        criteria.setOpenId(ATMRContext.getContext().getOpenId());
        criteria.setUserName(resources.getUserName());
        List<UserFamilyMembersDto> list = queryAll(criteria);
        if (CollectionUtils.isNotEmpty(list)){
            throw new BadRequestException("名称重复无需添加");
        }
        return userFamilyMembersMapper.toDto(userFamilyMembersRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(UserFamilyMembers resources) {
        UserFamilyMembers userFamilyMembers = userFamilyMembersRepository.findById(resources.getMemberId()).orElseGet(UserFamilyMembers::new);
        ValidationUtil.isNull( userFamilyMembers.getMemberId(),"UserFamilyMembers","id",resources.getMemberId());
        userFamilyMembers.copy(resources);
        userFamilyMembersRepository.save(userFamilyMembers);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long memberId : ids) {
            userFamilyMembersRepository.deleteById(memberId);
        }
    }

    @Override
    public void download(List<UserFamilyMembersDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (UserFamilyMembersDto userFamilyMembers : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("openId", userFamilyMembers.getOpenId());
            map.put("成员角色", userFamilyMembers.getMemberRole());
            map.put("成员名称", userFamilyMembers.getUserName());
            map.put("成员年龄", userFamilyMembers.getMemberAge());
            map.put("成员性别", userFamilyMembers.getMemberSex());
            map.put("创建时间", userFamilyMembers.getCreateTime());
            map.put("创建人", userFamilyMembers.getCreateby());
            map.put("更新时间", userFamilyMembers.getUpdateTime());
            map.put("更新人", userFamilyMembers.getUpdateby());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}